// pages/transfer/index.js
import { BaseModel } from "../../models/base";
Page({
  data: {
    fromAccount: {
      id: '',
      name: "",
      balance: "0"
    },
    toAccount: {
      id: "",
      name: ""
    },
    form: {
      anchorId: 0,
      advertiserId: 0,
      amount: 0,
      remark: ''
    },
    advertiserList : [],
    transferAmount: "5,000.00",
    remark: "",
    canTransfer: true,
    itemList: [],
    checkAdvertiserList: [],
  },

  // 切换账户
  switchAccount() {
    let that = this
    console.log(this.data.itemList)
    wx.showActionSheet({
      itemList: that.data.itemList,
      success: (res) => {
        let index = res.tapIndex, data = that.data.advertiserList[index],
        id = data.id, name = data.name, advertiserName = data.advertiserName,
        checkAdvertiserList = that.data.checkAdvertiserList;
        console.log("选择了第" + index + "个", "得到的数据" + data)
        that.setData({
          'fromAccount.id': name,
          'fromAccount.name': advertiserName,
          'form.anchorId': id
        })
        checkAdvertiserList = checkAdvertiserList.slice(index, 1)
        that.setData({checkAdvertiserList: checkAdvertiserList})
        that.getAdvertiserAvailableAmount()
      }
    });
  },

  // 选择转入的账户
  swichAdvertiser() {
    console.log("ok")
    let that = this;
    wx.showActionSheet({
      itemList: that.data.checkAdvertiserList,
      success: (res) => {
        let index = res.tapIndex, data = that.data.advertiserList[index],
        name = data.name, advertiserName = data.advertiserName
        that.setData({
          'toAccount.id': name,
          'toAccount.name': advertiserName,
          'form.advertiserId': id
        })
      }
    })
  },

  // 更新广告主可用的金额
  getAdvertiserAvailableAmount() {
    let baseModel = new BaseModel(), that = this;
    baseModel.getAdvertiserAvailableAmount(this.data.form.anchorId).then(res => {
      if (res.code == 200) {
        let amount = res.data
        that.setData({
          'fromAccount.balance': amount
        })
      }
    })
  },

  // 获取广告主的列表
  getAdvertiserList() {
    let baseModel = new BaseModel(), that = this;
    console.log(this.data.itemList)
    baseModel.getAdvertiserList().then(res => {
      if (res.code == 200) {
        let data = res.data, list = [];
        that.setData({advertiserList: data})
        data.map(item => {
          list.push(item.name + "(" + item.advertiserName + ")")
        });

        that.setData({itemList: list})
      }
    })
  },

  // 使用其他ID转出
  useOtherAccount() {
    wx.navigateTo({
      url: '/pages/other-account/index'
    });
  },

  // 转入ID输入
  onToAccountInput(e) {
    const value = e.detail.value;
    this.setData({
      'toAccount.id': value,
      'form.advertiserId': value
    });
  },

  // 金额输入
  onAmountInput(e) {
    let value = e.detail.value;
    
    // 移除非数字和小数点
    value = value.replace(/[^\d.]/g, '');
    
    // 处理小数点后只能有两位
    if (value.includes('.')) {
      const parts = value.split('.');
      if (parts[1].length > 2) {
        parts[1] = parts[1].substring(0, 2);
        value = parts.join('.');
      }
    }
    
    // 添加千位分隔符（仅当有整数部分时）
    if (value && !value.includes('.')) {
      value = value.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    }
    
    this.setData({
      'form.amount': value
    });
    this.validateForm();
  },

  goBack() {
    wx.navigateBack()
  },

  // 备注输入
  onRemarkInput(e) {
    this.setData({
      'form.remark': e.detail.value
    });
  },

  // 全部转出
  transferAll() {
    this.setData({
      'form.amount': this.data.fromAccount.balance
    });
  },

  // 验证表单
  validateForm() {
    const { toAccount, transferAmount, fromAccount } = this.data;
    
    // 移除金额中的逗号进行验证
    const amount = parseFloat(transferAmount.replace(/,/g, ''));
    const balance = parseFloat(fromAccount.balance.replace(/,/g, ''));
    
    const canTransfer = toAccount.id && toAccount.id.length > 0 && 
                       amount > 0 && amount <= balance;
    
    this.setData({
      canTransfer
    });
  },

  // 确认转账
  confirmTransfer() {
    wx.showLoading({
      title: '处理中...',
    });
    let baseModel = new BaseModel();
    baseModel.transfer(this.data.form).then(res => {
      wx.showToast({
        title: res.message,
        icon: "none"
      })

      wx.hideLoading();
    })
    
    // 显示加载中

    
  
  },

  // 重置表单
  resetForm() {
    this.setData({
      transferAmount: "",
      remark: "",
      canTransfer: false
    });
  },

  onLoad(options) {
    // 页面加载时的逻辑
    this.getAdvertiserList()
  },

  onReady() {
    // 页面渲染完成时的逻辑
  },

  onShow() {
    // 页面显示时的逻辑
  }
});